<template>
  <div class="order-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="queryParams" class="form-inline">
        <el-form-item label="订单号">
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="售货机">
          <el-select v-model="queryParams.machineId" placeholder="请选择售货机" clearable>
            <el-option
              v-for="machine in machineList"
              :key="machine.id"
              :label="machine.name"
              :value="machine.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单列表 -->
    <el-table
      v-loading="loading"
      :data="orderList"
      border
      style="width: 100%"
    >
      <el-table-column prop="orderNo" label="订单号" width="180" />
      <el-table-column prop="machineName" label="售货机" />
      <el-table-column prop="productName" label="商品" />
      <el-table-column prop="quantity" label="数量" width="80" align="center" />
      <el-table-column prop="totalPrice" label="金额" width="100">
        <template #default="{ row }">
          ¥{{ row.totalPrice.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleDetail(row)">详情</el-button>
          <el-button 
            v-if="row.status === 'PENDING'"
            type="success" 
            link 
            @click="handlePay(row)"
          >
            支付
          </el-button>
          <el-button 
            v-if="row.status === 'PENDING'"
            type="danger" 
            link 
            @click="handleCancel(row)"
          >
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="detailDialogVisible"
      width="600px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ orderDetail.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(orderDetail.status)">
            {{ getStatusLabel(orderDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="售货机">{{ orderDetail.machineName }}</el-descriptions-item>
        <el-descriptions-item label="商品">{{ orderDetail.productName }}</el-descriptions-item>
        <el-descriptions-item label="数量">{{ orderDetail.quantity }}</el-descriptions-item>
        <el-descriptions-item label="金额">¥{{ orderDetail.totalPrice?.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ orderDetail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ orderDetail.payTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="取消时间" v-if="orderDetail.status === 'CANCELLED'">
          {{ orderDetail.cancelTime }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 支付对话框 -->
    <el-dialog
      title="订单支付"
      v-model="payDialogVisible"
      width="400px"
      append-to-body
    >
      <div class="pay-dialog">
        <div class="pay-amount">
          支付金额：<span class="amount">¥{{ currentOrder?.totalPrice?.toFixed(2) }}</span>
        </div>
        <div class="pay-qrcode">
          <img src="@/assets/pay-qrcode.png" alt="支付二维码">
        </div>
        <div class="pay-tip">
          请使用支付宝扫码支付
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderList, getOrderDetail, cancelOrder, payOrder } from '@/api/order'
import { getMachineList } from '@/api/machine'

// 状态选项
const statusOptions = [
  { label: '待支付', value: 'PENDING' },
  { label: '已支付', value: 'PAID' },
  { label: '已完成', value: 'COMPLETED' },
  { label: '已取消', value: 'CANCELLED' }
]

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  orderNo: '',
  machineId: undefined,
  status: undefined,
  startDate: undefined,
  endDate: undefined
})

// 日期范围
const dateRange = ref([])

// 列表数据
const loading = ref(false)
const orderList = ref([])
const total = ref(0)
const machineList = ref([])

// 获取订单列表
const getList = async () => {
  try {
    loading.value = true
    const { data } = await getOrderList(queryParams)
    orderList.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取订单列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取售货机列表
const getMachines = async () => {
  try {
    const { data } = await getMachineList()
    machineList.value = data
  } catch (error) {
    console.error('获取售货机列表失败:', error)
  }
}

// 日期范围变化
const handleDateRangeChange = (val) => {
  if (val) {
    queryParams.startDate = val[0]
    queryParams.endDate = val[1]
  } else {
    queryParams.startDate = undefined
    queryParams.endDate = undefined
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮点击
const resetQuery = () => {
  queryParams.orderNo = ''
  queryParams.machineId = undefined
  queryParams.status = undefined
  queryParams.startDate = undefined
  queryParams.endDate = undefined
  dateRange.value = []
  handleQuery()
}

// 分页相关方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 订单详情相关
const detailDialogVisible = ref(false)
const orderDetail = ref({})

// 查看详情
const handleDetail = async (row) => {
  try {
    const { data } = await getOrderDetail(row.id)
    orderDetail.value = data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取订单详情失败:', error)
  }
}

// 支付相关
const payDialogVisible = ref(false)
const currentOrder = ref(null)

// 支付按钮点击
const handlePay = (row) => {
  currentOrder.value = row
  payDialogVisible.value = true
}

// 取消订单
const handleCancel = (row) => {
  ElMessageBox.confirm(
    '确认取消该订单吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await cancelOrder(row.id)
      ElMessage.success('取消成功')
      getList()
    } catch (error) {
      console.error('取消订单失败:', error)
    }
  })
}

// 获取状态标签类型
const getStatusType = (status) => {
  const map = {
    'PENDING': 'warning',
    'PAID': 'success',
    'COMPLETED': 'success',
    'CANCELLED': 'info'
  }
  return map[status] || ''
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const option = statusOptions.find(item => item.value === status)
  return option ? option.label : status
}

onMounted(() => {
  getList()
  getMachines()
})
</script>

<style scoped>
.order-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.form-inline {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.pay-dialog {
  text-align: center;
  padding: 20px;
}

.pay-amount {
  font-size: 16px;
  margin-bottom: 20px;
}

.amount {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
}

.pay-qrcode {
  margin-bottom: 20px;
}

.pay-qrcode img {
  width: 200px;
  height: 200px;
}

.pay-tip {
  color: #909399;
  font-size: 14px;
}
</style> 